﻿using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;

public static class SpriteSlicer {

    [@MenuItem("Assets/SpriteSlicer", false, 2200)]
    public static void SpriteSlice() {
        var image = Selection.activeObject as Texture2D;
        if (image == null) {
            return;
        }

        var path = AssetDatabase.GetAssetPath(image);
        var rootPath = Path.GetDirectoryName(path);
        var texImp = AssetImporter.GetAtPath(path) as TextureImporter;
        AssetDatabase.CreateFolder(rootPath, image.name);

        foreach (SpriteMetaData metaData in texImp.spritesheet) {
            var myimage = new Texture2D((int)metaData.rect.width, (int)metaData.rect.height);
            for (int y = (int)metaData.rect.y; y < metaData.rect.y + metaData.rect.height; y++) {
                for (int x = (int)metaData.rect.x; x < metaData.rect.x + metaData.rect.width; x++)
                    myimage.SetPixel(x - (int)metaData.rect.x, y - (int)metaData.rect.y, image.GetPixel(x, y));
            }
            if (myimage.format != TextureFormat.ARGB32 && myimage.format != TextureFormat.RGB24) {
                Texture2D newTexture = new Texture2D(myimage.width, myimage.height);
                newTexture.SetPixels(myimage.GetPixels(0), 0);
                myimage = newTexture;
            }
            var pngData = myimage.EncodeToPNG();
            //AssetDatabase.CreateAsset(myimage, rootPath + "/" + image.name + "/" + metaData.name + ".png");
            File.WriteAllBytes(rootPath + "/" + image.name + "/" + metaData.name + ".png", pngData);
            AssetDatabase.Refresh();
        }
    }

}

